package com.sciyichen.tcpclientbytes;

import android.os.Build;
import android.util.Base64;
import com.alibaba.fastjson.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class TcpClientBytesPluginImpl implements TcpClientBytesPlugins {
    private static final String TAG = "TcpClientBytesPluginImpl";
    private static final Logger logger = Logger.getLogger(TAG);
    private Socket socket;
    private OutputStream outputStream;
    private ExecutorService executorService;
    private  Consumer<String>  stringCallback;
    private  Consumer<byte[]>   byteArrayCallback;
    private Consumer<String> byteArrayBase64StrCallback;
    // TcpClientBytesPluginImpl 类中添加的方法
    private final AtomicBoolean isReceiving = new AtomicBoolean(false);
    private DataInputStream inputStream;
    private OnDataReceivedCallback dataCallback;
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private final AtomicBoolean isConnected = new AtomicBoolean(false);
// 在 TcpClientBytesPluginImpl 中

    private String lastHost;
    private int lastPort;
    private int lastTimeout;
    private static final int[] CCITT_TABLE = {
            0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
            0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
            0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
            0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
            0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
            0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
            0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
            0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
            0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
            0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
            0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
            0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
            0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
            0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
            0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
            0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
            0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
            0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
            0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
            0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
            0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
            0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
            0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
            0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
            0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
            0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
            0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
            0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
            0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
            0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
            0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
            0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
    };
    @Override
    public boolean isConnected() {
        return isConnected.get() && socket != null && socket.isConnected();
    }
    @Override
    public int crcCcitt(byte[] data, int crc) {
        int length = data.length;
        for (int i = 0; i < length; i++) {
            int index = ((crc >> 8) ^ (data[i] & 0xff)) & 0xff;
            crc = (CCITT_TABLE[index] ^ (crc << 8)) & 0xffff;
        }
        return ~crc & 0xffff;
    }

    @Override
    public byte[] buildPacketFromJson(String outstr, int checksum) {
        byte[] data = outstr.getBytes();
        int dataSize = data.length;
        ByteBuffer packet = ByteBuffer.allocate(10 + dataSize);
        packet.put((byte) 0x7E);
        packet.put((byte) 0xE7);
        packet.putInt(dataSize);
        packet.putShort((short) checksum);
        byte[] header = new byte[8];
        packet.position(0);
        packet.get(header);
        int headerCrc = crcCcitt(header, 0);
        packet.putShort((short) headerCrc);
        packet.put(data);
        return packet.array();
    }
    @Override
    public  String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
    @Override
    public byte[] hexToBytes(String hex) {
        int length = hex.length();
        byte[] result = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            result[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return result;
    }
    @Override
    public Object[] bufferToJson(byte[] pBuffer, int nStart, int nOffset) {
       List<JSONObject>  jdata = new ArrayList<>();
        for (int i = nStart; i < nOffset; i++) {
            if (pBuffer[i] == (byte) 0x7E) {
                if (i + 1 < nOffset && pBuffer[i + 1] == (byte) 0xE7) {
                    if (nOffset > i + 8) {
                        int crc0 = crcCcitt(java.util.Arrays.copyOfRange(pBuffer, i, i + 8), 0);
                        int crc1 = ((pBuffer[i + 8] & 0xff) << 8) | (pBuffer[i + 9] & 0xff);
                        if (crc0 == crc1) {
                            int nPacketSize = ((pBuffer[i + 2] & 0xff) << 24) | ((pBuffer[i + 3] & 0xff) << 16) |
                                    ((pBuffer[i + 4] & 0xff) << 8) | (pBuffer[i + 5] & 0xff);
                            if (i + 10 + nPacketSize <= nOffset) {
                                int dataCrc = crcCcitt(java.util.Arrays.copyOfRange(pBuffer, i + 10, i + 10 + nPacketSize), 0);
                                int packetCrc = ((pBuffer[i + 6] & 0xff) << 8) | (pBuffer[i + 7] & 0xff);
                                if (dataCrc == packetCrc) {
                                    try {
                                        String jsonStr = new String(java.util.Arrays.copyOfRange(pBuffer, i + 10, i + 10 + nPacketSize), "UTF-8");
                                        jdata.add(JSONObject.parseObject(jsonStr));
                                        nStart = i + 10 + nPacketSize;
                                        break;
                                    } catch (Exception e) {
                                        System.out.println("JSON decode error: " + e.getMessage());
                                    }
                                }
                            } else {
                                nStart = i;
                                break;
                            }
                        }
                    } else {
                        nStart = i;
                        break;
                    }
                } else {
                    nStart = i;
                    break;
                }
            }
        }
        return new Object[]{nStart, nOffset,  JSONObject.toJSONString(jdata)};
    }
    @Override
    public List<String> getDataFromBytesBase64(String nBytesBase64, int buffSize) {
        byte[] nBytes = Base64.decode(nBytesBase64, Base64.DEFAULT);
        // 固定值方式（适合大多数情况）
//        int buffSize = 4096; // 4KB，足够处理大多数JSON数据包

//// 动态计算方式（适合数据大小变化较大的情况）
//        int minBufferSize = 1024; // 最小缓冲区大小
//        int calculatedSize = (int)(nBytes.length * 1.2); // 计算大小并增加20%余量
//        int buffSize = Math.max(minBufferSize, calculatedSize); // 取较大值
       return getAJsonPacketFromSocket(nBytes, buffSize);
    }
    @Override
    public List<String> getAJsonPacketFromSocket(byte[] nBytes, int buffSize) {
        byte[] pBuffer = new byte[0];
        int nOffset = 0;
        int nStart = 0;
        int MAX_BUFFER_SIZE = 65536;
        List<String> jlist = new ArrayList<>();

        while (true) {
            if (nOffset + buffSize > MAX_BUFFER_SIZE) {
                pBuffer = java.util.Arrays.copyOfRange(pBuffer, nStart, pBuffer.length);
                nOffset = pBuffer.length;
                nStart = 0;
            }
            try {
                if (nBytes == null || nBytes.length == 0) {
                    break;
                }
                byte[] newBuffer = new byte[pBuffer.length + nBytes.length];
                System.arraycopy(pBuffer, 0, newBuffer, 0, pBuffer.length);
                System.arraycopy(nBytes, 0, newBuffer, pBuffer.length, nBytes.length);
                pBuffer = newBuffer;
                nOffset += nBytes.length;
            } catch (Exception e) {
                System.out.println("Socket receive error: " + e.getMessage());
                break;
            }
            Object[] res = bufferToJson(pBuffer, nStart, nOffset);
            nStart = (int) res[0];
            nOffset = (int) res[1];
            if (res[2] != null) {
                jlist.add( (String) res[2]);
            }
            if (!jlist.isEmpty()) {
                return jlist;
            }
        }
        return jlist;
    }
    @Override
    public byte[] tcpClientBytes(String host, int port, String base64str, int buffSize, int timeout) {
        try (Socket clientSocket = new Socket(host, port)) {
            if (timeout<100){
                timeout=1000;
            }
            clientSocket.setSoTimeout(timeout);
            byte[] decodedBytes = Base64.decode(base64str, Base64.DEFAULT);
            OutputStream outputStream = clientSocket.getOutputStream();
            outputStream.write(decodedBytes);

            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
            InputStream inputStream = clientSocket.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    responseStream.write(buffer, 0, bytesRead);
                }
            } catch (java.net.SocketTimeoutException e) {
                System.out.println("Read operation timed out.");
            }
            return responseStream.toByteArray();
        } catch (IOException e) {
            String str = "Socket error: " + e.getMessage();
            return str.getBytes();
        }
    }

    @Override
    public byte[] tcpClientBytes(String host, int port, String base64str, int buffSize) {
        return tcpClientBytes(host, port, base64str, buffSize, 1000);
    }
    @Override
    public List<String> tcpClientByte(String host, int port, String base64str, int buffSize) {
        return tcpClientByte(host, port, base64str, buffSize, 1000);
    }
    @Override
    public List<String> tcpClientByte(String host, int port, String base64str, int buffSize, int timeout) {
        try (Socket clientSocket = new Socket(host, port)) {
            if (timeout<100){
                timeout=1000;
            }
            clientSocket.setSoTimeout(timeout);
            byte[] decodedBytes =  Base64.decode(base64str, Base64.DEFAULT);
            OutputStream outputStream = clientSocket.getOutputStream();
            outputStream.write(decodedBytes);

            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
            InputStream inputStream = clientSocket.getInputStream();
            byte[] buffer = new byte[buffSize];
            int bytesRead;
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    responseStream.write(buffer, 0, bytesRead);
                }
            } catch (java.net.SocketTimeoutException e) {
                System.out.println("Read operation timed out.");
            }
            byte[] response = responseStream.toByteArray();
            return getAJsonPacketFromSocket(response, buffSize);
        } catch (IOException e) {
            System.out.println("Socket error: " + e.getMessage());
            return new ArrayList<>();
        }
    }
    private boolean isConnectionValid() {
        // 检查连接标志和Socket实际状态
        boolean isValid = isConnected.get()
                && socket != null
                && socket.isConnected()
                && !socket.isClosed()
                && !socket.isOutputShutdown();

        // 额外验证：尝试发送空字节（不影响实际数据）
        if (isValid) {
            try {
                socket.sendUrgentData(0); // 发送紧急数据，仅用于验证连接
            } catch (IOException e) {
                LogUtils.w(TAG, "连接验证失败: " + e.getMessage());
                isValid = false;
            }
        }

        return isValid;
    }
    // 检查网络权限
    private void handleSuccessCallback(Consumer<String> callback, String result) {
        if (callback != null) {
            callback.accept(result);
        }
    }

    private void handleErrorCallback(Consumer<String> callback, String error) {
        if (callback != null) {
            callback.accept(error);
            isConnected.set(false);
        }
    }
    @Override
    public void connect(String host, int port, int timeout,
                        Consumer<String> successCallback, Consumer<String> errorCallback) {
        // 保存连接参数用于重连
        this.lastHost = host;
        this.lastPort = port;
        this.lastTimeout = timeout;
        try {
            logger.info("开始连接到 " + host + ":" + port + "，超时: " + timeout + "ms");
            int effectiveTimeout = timeout > 0 ? timeout : 15000;

            socket = new Socket();
            socket.connect(new InetSocketAddress(host, port), effectiveTimeout);
            socket.setSoTimeout(effectiveTimeout);

            // 初始化输入输出流
            inputStream = new DataInputStream(socket.getInputStream());
            outputStream = socket.getOutputStream();

            // 初始化线程池
            executorService = Executors.newSingleThreadExecutor();

            logger.info("连接成功，Socket: " + socket);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                successCallback.accept("连接成功");
            }
            isConnected.set(true);
            isRunning.set(true);

//            // 启动数据接收线程（添加状态检查）
//            if (!isReceiving.get()) {
//                startReceiveThread();
//            }
        } catch (UnknownHostException e) {
            String errorMsg = "未知主机: " + e.getMessage();
            logger.severe(errorMsg);
            errorCallback.accept(errorMsg);
        } catch (ConnectException e) {
            String errorMsg = "连接被拒绝: " + e.getMessage();
            logger.severe(errorMsg);
            errorCallback.accept(errorMsg);
        } catch (SocketTimeoutException e) {
            String errorMsg = "连接超时: " + e.getMessage();
            logger.severe(errorMsg);
            errorCallback.accept(errorMsg);
        } catch (IOException e) {
            String errorMsg = "IO异常: " + e.getMessage();
            logger.severe(errorMsg);
            errorCallback.accept(errorMsg);
        } catch (Exception e) {
            String errorMsg = "连接异常: " + e.getMessage();
            logger.severe(errorMsg);
            errorCallback.accept(errorMsg);
        }
    }
    private boolean reconnectIfNeeded() {
        if (lastHost == null || !isConnected.get()) {
            return false;
        }

        LogUtils.i(TAG, "尝试重连到: " + lastHost + ":" + lastPort);

        try {
            closeQuietly(); // 确保旧连接已关闭

            // 创建新连接
            socket = new Socket();
            socket.connect(new InetSocketAddress(lastHost, lastPort), lastTimeout);
            socket.setSoTimeout(lastTimeout);

            // 初始化输入输出流
            inputStream = new DataInputStream(socket.getInputStream());
            outputStream = socket.getOutputStream();

            isConnected.set(true);
            isRunning.set(true);

            // 重启接收线程
            startReceiveThread();

            LogUtils.i(TAG, "重连成功");
            return true;
        } catch (Exception e) {
            LogUtils.e(TAG, "重连失败: " + e.getMessage());
            isConnected.set(false);
            return false;
        }
    }
    @Override
    public void sendBase64Str(String base64str, Consumer<String> successCallback, Consumer<String> errorCallback) {
        if (!isConnected.get() || socket == null || !socket.isConnected()) {
            if (errorCallback != null) {
                errorCallback.accept("连接已关闭");
            }
            return;
        }

        try {
            byte[] decodedBytes =  Base64.decode(base64str, Base64.DEFAULT);
            outputStream.write(decodedBytes);
            outputStream.flush();
            if (successCallback != null) {
                successCallback.accept("发送成功");
            }
        } catch (IOException e) {
            LogUtils.e(TAG, "发送失败: " + e.getMessage());
            if (errorCallback != null) {
                errorCallback.accept("发送失败: " + e.getMessage());
            }
        }
    }
    @Override
    public void sendBytes(byte[] data, Consumer<String> successCallback, Consumer<String> errorCallback) {
        // 双重检查锁模式
        if (!isConnectionValid()) {
            // 尝试自动重连（仅在连接丢失但标志未更新时有效）
            if (isConnected.get() && !reconnectIfNeeded()) {
                if (errorCallback != null) {
                    errorCallback.accept("连接已关闭，重连失败");
                }
                return;
            }
        }

        try {
            outputStream.write(data);
            outputStream.flush();
            if (successCallback != null) {
                successCallback.accept("发送成功");
            }
        } catch (IOException e) {
            LogUtils.e(TAG, "发送失败: " + e.getMessage());
            isConnected.set(false);

            // 尝试重连
            if (reconnectIfNeeded()) {
                try {
                    // 重连后重试发送
                    outputStream.write(data);
                    outputStream.flush();
                    if (successCallback != null) {
                        successCallback.accept("重连后发送成功");
                    }
                    return;
                } catch (IOException ex) {
                    LogUtils.e(TAG, "重连后发送仍失败: " + ex.getMessage());
                }
            }

            if (errorCallback != null) {
                errorCallback.accept("发送失败: " + e.getMessage());
            }
        }
    }
    @Override
    public void send(String data, Consumer<String> successCallback, Consumer<String> errorCallback) {
        // 发送方法改进
        try {
            if (isConnected.get() && socket != null && socket.isConnected()) {
                byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
                outputStream.write(bytes);
                outputStream.flush();
                if (successCallback != null) {
                    successCallback.accept("发送成功");
                }
            } else {
                if (errorCallback != null) {
                    errorCallback.accept("连接已关闭");
                }
            }
        } catch (IOException e) {
            LogUtils.e(TAG, "发送失败: " + e.getMessage());
            if (errorCallback != null) {
                errorCallback.accept("发送失败: " + e.getMessage());
            }
        }
    }

    @Override
    public void close(Consumer<String> successCallback, Consumer<String> errorCallback) {
        // 关闭方法改进
        try {
            isRunning.set(false);
            isConnected.set(false);

            if (executorService != null) {
                executorService.shutdownNow();
                executorService = null;
            }

            closeQuietly();

            if (successCallback != null) {
                successCallback.accept("关闭成功");
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "关闭失败: " + e.getMessage());
            if (errorCallback != null) {
                errorCallback.accept("关闭失败: " + e.getMessage());
            }
        } finally {
            // 清理回调引用
            stringCallback = null;
            byteArrayCallback = null;
            byteArrayBase64StrCallback = null;
        }
    }
    // 启动持续数据接收
    public void startContinuousDataReceiving() {
        if (isReceiving.get()) return;

        isReceiving.set(true);
        try {
            if (socket == null || socket.isClosed()) {
                throw new IOException("Socket未连接或已关闭");
            }

            inputStream = new DataInputStream(socket.getInputStream());
            byte[] buffer = new byte[1024]; // 缓冲区大小可配置

            while (isReceiving.get() && !socket.isClosed()) {
                int bytesRead = inputStream.read(buffer);
                if (bytesRead > 0) {
                    // 提取有效数据
                    byte[] data = new byte[bytesRead];
                    System.arraycopy(buffer, 0, data, 0, bytesRead);

                    // 回调数据
                    if (dataCallback != null) {
                        dataCallback.onDataReceived(data);
                    }
                } else if (bytesRead == -1) {
                    // 连接已关闭
                    isReceiving.set(false);
                    break;
                }
            }
        } catch (IOException e) {

                if (isReceiving.get()) {
                    logger.log(Level.SEVERE, "数据接收异常，尝试重连", e);
                    // 此处添加重连逻辑
//                    reconnect(host, port, timeout, successCallback, errorCallback);

            }
        } finally {
            isReceiving.set(false);
            closeQuietly(inputStream);
        }
    }

    // 停止数据接收
    public void stopDataReceiver() {
        isReceiving.set(false);
        closeQuietly(inputStream);
    }

    // 关闭资源工具方法
    private void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.log(Level.WARNING, "关闭资源异常", e);
            }
        }
    }

    // 数据接收回调接口
    public interface OnDataReceivedCallback {
        void onDataReceived(byte[] data);
    }
    @Override
    public void setDataByteArrayCallback(Consumer<byte[]> callback) {
        // 回调设置改进（线程安全）
        this.byteArrayCallback = callback;
        // 关键：将 Consumer 包装为 OnDataReceivedCallback
//        this.dataCallback = data -> {
//            if (callback != null) {
//                callback.accept(data);
//            }
//        };
        // 关键：将 Consumer 包装为 OnDataReceivedCallback
        this.dataCallback = new OnDataReceivedCallback() {
            @Override
            public void onDataReceived(byte[] data) {
                if (callback != null) {
                    callback.accept(data);
                }
            }
        };
    }

    @Override
    public void setDataByteArrayBase64StrCallback(Consumer<String> callback) {
        // 回调设置改进（线程安全）
        this.byteArrayBase64StrCallback = callback;
    }

    @Override
    public void setStringCallback(Consumer<String> callback) {
        // 回调设置改进（线程安全）
        this.stringCallback = callback;
    }
    private void processReceivedData(byte[] data) {

        // 处理数据并触发回调（添加线程安全检查）
        if (byteArrayCallback != null) {
            byteArrayCallback.accept(data);
        }

        if (stringCallback != null) {
            String str = new String(data, StandardCharsets.UTF_8);
            stringCallback.accept(str);
        }

        if (byteArrayBase64StrCallback != null) {
            String base64String = Base64.encodeToString(data, Base64.DEFAULT);
            byteArrayBase64StrCallback.accept(base64String);
        }
    }

    private void startReceiveThread() {
        if (isReceiving.getAndSet(true)) {
            logger.info("接收线程已在运行，无需重复启动");
            return;
        }
        executorService.submit(() -> {
            byte[] buffer = new byte[4096];
            int bytesRead;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            try {
                while (isRunning.get() && (bytesRead = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                    byte[] data = baos.toByteArray();
                    if (data.length > 0) {
                        processReceivedData(data);
                    }
                    baos.reset();
                }

                } catch (SocketException e) {
                    LogUtils.w(TAG, "接收线程: Socket异常，尝试重连: " + e.getMessage());
                    reconnectIfNeeded();
                } catch (IOException e) {
                    if (isRunning.get()) {
                        LogUtils.e(TAG, "接收线程: 接收数据失败: " + e.getMessage());
                        reconnectIfNeeded();
                    }
                } finally {
                    if (isRunning.get()) {
                        LogUtils.w(TAG, "接收线程: 连接已关闭，尝试重连");
                        reconnectIfNeeded();
                    }
                    isRunning.set(false);
                    isConnected.set(false);
                }
        });
    }

    // 辅助方法：安静地关闭资源，不抛出异常
    private void closeQuietly() {
        LogUtils.i(TAG, "关闭所有网络资源");

        isRunning.set(false);
        isConnected.set(false);

        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            LogUtils.w(TAG, "关闭输入流失败: " + e.getMessage());
        }

        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            LogUtils.w(TAG, "关闭输出流失败: " + e.getMessage());
        }

        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            LogUtils.w(TAG, "关闭Socket失败: " + e.getMessage());
        }

        // 重置资源引用
        inputStream = null;
        outputStream = null;
        socket = null;
    }

    @Override
    public void tcpClient(String ip, int port) {
        String jsonstr = "{\"request\":\"QueryStatus\"}";
        int checksum = crcCcitt(jsonstr.getBytes(), 0);
        byte[] byteArray = buildPacketFromJson(jsonstr, checksum);
        String base64String = Base64.encodeToString( byteArray, Base64.DEFAULT);
      List<String> list=  tcpClientByte(ip, port, base64String, 1024);
        LogUtils.i(TAG, "发送查询状态请求: " + base64String);
    }
}